﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Drawing.Imaging;

namespace Team6_Algorithms.Binary
{
    public class Erosion
    {
        /// <summary>
        /// This function will Erode the given bitmap.
        /// The input image has to be black - white ( binary ) for this function.
        /// </summary>
        /// <param name="srcImage">Bitmap to erose</param>
        /// <returns>Returns erosed bitmap</returns>
        public Bitmap Erode(Bitmap srcImage)
        {
            Bitmap returnImage = new Bitmap(srcImage.Width, srcImage.Height);
            BitmapData srcData = srcImage.LockBits(new Rectangle(0, 0,
                srcImage.Width, srcImage.Height), ImageLockMode.ReadOnly,
                PixelFormat.Format24bppRgb);
            BitmapData desData = returnImage.LockBits(new Rectangle(0, 0, returnImage.Width,
                returnImage.Height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);

            //erosion mask
            byte[,] mask = new byte[3, 3] { 
                {0,1,0},
                {1,1,1},
                {0,1,0}
            };

            unsafe
            {
                byte* ptr = (byte*)srcData.Scan0;
                byte* tptr = (byte*)desData.Scan0;

                ptr += srcData.Stride + 3;
                tptr += srcData.Stride + 3;

                int remain = srcData.Stride - srcData.Width * 3;

                for (int i = 1; i < srcData.Height - 1; i++)
                {
                    for (int j = 1; j < srcData.Width - 1; j++)
                    {

                        if (ptr[0] != 255)
                        {

                            byte* temp = ptr - srcData.Stride - 3;
                            bool condition = false;

                            for (int k = 0; k < 3; k++)
                            {
                                for (int l = 0; l < 3; l++)
                                {
                                    if (mask[k, l] == 1 && temp[0] == 255)
                                    {
                                        condition = true;
                                    }
                                    temp += 3;
                                }
                                temp += srcData.Stride - 9;
                            }
                            if (condition)
                            {
                                tptr[0] = tptr[1] = tptr[2] = 255;
                            }
                        }
                        ptr += 3;
                        tptr += 3;
                    }
                    ptr += remain + 6;
                    tptr += remain + 6;
                }
            }
            srcImage.UnlockBits(srcData);
            returnImage.UnlockBits(desData);
            return returnImage;
        }
    }
}
